<?php


namespace App\Repositories;


use App\Models\ProductBook as Model;
use App\Models\ProductCustoms;
use Exception;
use LTools\Repositories\RepositoryAbstract;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

class ProductBook extends RepositoryAbstract
{
    /**
     * ProductBook constructor.
     * @param Model $model
     * @author luffyzhao@vip.126.com
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $values
     * @return void
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @author luffyzhao@vip.126.com
     */
    public function store(array $values)
    {
        $file = public_path($values['file']);
        $reader = new Xlsx();
        $spreadsheet = $reader->load($file);

        $esmNo = $spreadsheet->getSheet(0)->getCellByColumnAndRow(4, 2)->getValue();
        if (app(System::class)->getGroup('customs')['ems_no'] !== $esmNo) {
            throw new Exception("请检查你的账册号是否和系统的一致？！");
        }

        $sheet = $spreadsheet->getSheet(1);
        // 最多只能上传100行数据
        if ($sheet->getHighestRow() > 102) {
            throw new Exception(sprintf("最多只能上传100行数据:%d", $sheet->getHighestRow()));
        }

        foreach ($sheet->getRowIterator(3) as $index => $item) {
            try {
                $array = [];
                foreach ($item->getCellIterator('A', 'E') as $key => $value) {
                    $array[$key] = $value->getValue();
                }
                try {
                    $customs = ProductCustoms::query()
                        ->where('unique', '=', $array['B'])
                        ->firstOrFail();
                } catch (Exception $exception) {
                    throw new Exception(sprintf("序号[{$array['A']}]系统找不以对应商品"));
                }
                if ($customs->getAttribute('code') != $array['C']) {
                    throw new Exception(sprintf("序号[%s]海关编码不正确！%s=>%s", $array['A'], $array['C'], $customs['code']));
                }
                if ($customs->getAttribute('name') != $array['D']) {
                    throw new Exception(sprintf("序号[%s]海关品名不正确！%s=>%s", $array['A'], $array['D'], $customs['name']));
                }
                if ($customs->getAttribute('element') != $array['E']) {
                    throw new Exception(sprintf("序号[%s]海关规格不正确！%s=>%s", $array['A'], $array['E'], $customs['element']));
                }

                $this->model->newQuery()->firstOrCreate([
                    'unique' => $array['B'],
                    'record_no' => $array['A'],
                ]);

            } catch (Exception $exception) {
                throw new Exception(sprintf("第 %d 行错误: %s", $index, $exception->getMessage()));
            }
        }
    }
}